var util = require('util.js');
const isProd = true;
var debug = false;
const host = isProd ? 'https://zy-api.hui520.com' : 'http://localhost';
const api = host + '/api/';
const uploadImageUrl = host + '/bussinessEntry';


// wx.request 的统一处理
function proc(url, data, method, header, cb, failcb, complatecb, aborted = false) {
	if (debug) {
    console.log("request:" + url);
		console.log(data);
	}
  
  const requestTask = wx.request({
    url: url,
    data: data,
    method: method,
    header: header,
    success: function (res) {
    	if (debug) {
	    	console.log("response:" + url);
	      console.log(res);
    	}
      if (res) {
        if (typeof cb == "function") {
          cb(res);
        }
      } else {
        util.toast('网络异常，请稍后再试', 'none', 2000);
        if (typeof failcb == "function") {
          failcb(res);
        }
      }
    },
    fail: function () {
      util.toast('网络异常，请稍后再试', 'none', 2000);
      if (typeof failcb == "function") {
        failcb();
      }
    },
    complete: function() {
      if (typeof complatecb == "function") {
        complatecb();
      }
    }
  })
  if (aborted) {
    requestTask.abort()
  }
}
// api调用的统一处理
function request(apiMethod, data, cb, failcb, complatecb, method = "POST", showLoading = true) {
    if (showLoading) {
      wx.showLoading()
    }

    // 检测设备网络状态
    wx.getNetworkType({
      success: function (res) {
        if (res.networkType == 'none') {
          wx.hideLoading()
          util.toast('当前无网络，请检查手机网络后再试', 'none', 2000);
          if (typeof failcb == "function") {
            return failcb();
          }
        } else {
          let header = { 'content-type': 'application/json' }
          let url = api + apiMethod;

          let token = getApp().globalData.token
          if (token) {
            url = url + ((url.indexOf("?") ? "&" : "?") + "s_token=" + token);
          }
          
          proc(url, data, method, header, function (res) {
            wx.hideLoading()
            if (res.statusCode === 200) {
              console.log(res.data);
              if (res.data && res.data.status === '0') {
                if (typeof cb == "function") {
                  cb(res.data.data);
                } 
              } else {
                util.toast(res.data.message, 'none', 2000);
                if (typeof failcb == "function") {
                  failcb();
                }
              }
            } else if (res.statusCode >= 500) {
              util.toast('服务器繁忙，请稍后再试', 'none', 2000)
              if (typeof failcb == "function") {
                failcb();
              }
            }
          }, function() {
            wx.hideLoading();
            if (typeof failcb == "function") {
                failcb();
            }
          }, function() {
            // wx.hideLoading();
            if (typeof complatecb == "function") {
              complatecb();
            }
          })
        }
      },
      fail: function() {
        wx.hideLoading();
        if (typeof failcb == "function") {
            return failcb();
        }
      }
    })
}

function uploadImage(apiMethod, filePath, data, cb, showLoading = true) {
  if (showLoading) {
    wx.showLoading()
  }

  wx.getNetworkType({
    success: function (res) {
      if (res.networkType == 'none') {
        wx.hideLoading()
        util.toast('当前无网络，请检查手机网络后再试', 'none', 2000)
      } else {
        let header = {'content-type': 'multipart/form-data' }
        let url = uploadImageUrl;
        
        if (!data) {
          data = {};
        }
        let module_action = apiMethod.split('/');
        data['module'] = module_action[0];
        data['action'] = module_action[1];

        let token = getApp().globalData.token
        if (token) {
          data['s_token'] = token;
        }
        console.log(data)
        wx.uploadFile({
          url: url,
          header: header,
          filePath: filePath,
          name: 'uploadFile',
          formData: data,
          success: (res) => {
            wx.hideLoading();
            if (res.statusCode === 200) {
              console.log(res);
              var data = res.data
              if(typeof data === 'string') {
                data = JSON.parse(data.trim());
              }
              if (data && data.status == '0') {
                return typeof cb == "function" && cb(data.data)
              } else {
                util.toast(data.message ? data.message : "未知错误", 'none', 2000)
              }
            } else if (res.statusCode >= 500) {
              util.toast('服务器繁忙，请稍后再试', 'none', 2000)
            }
          },
          fail: (res) => {
            console.error(res)
            util.toast('网络异常，请稍后再试', 'none', 2000)
          }
        });

        // if (aborted) {
        //   uploadTask.abort()
        // }
      }
    }
  });
}

// 微信登录
function login(apiMethod, data, cb, failcb) {
  wx.login({
    success: function (res) {
      if (res.code) {
        let params = {
          jsCode: res.code
        }
        request(apiMethod, params, function (res) {
          if (res) {
            // wx.setStorageSync('user', res)
            // if (res.token) {
            //     wx.setStorageSync('token', res.token);
            // }
            
            
            if (cb && typeof cb == "function") {
              cb(res)
            }
          } else {
            if (failcb && typeof failcb == "function") {
              failcb('登陆失败')
            }
          }
        }, 'POST', false)
      } else {
        if (failcb && typeof failcb == "function") {
          failcb(res.errMsg)
        }
        console.log('登录失败！' + res.errMsg)
      }
    }, fail(e) {
        console.log('login error ' + e.errMsg)
    }
  })
}


export function batchGetDictValues(dictCodes) {
  return request({
    url: '/dict/batchGetDictValues',
    method: 'post',
    params: {dictCodes: dictCodes}
  })
}

export function loadDictValue(dictCodes, cb) {
  let requestParams = {dictCodes: dictCodes}
  request('dict/batchGetDictValues', requestParams, function(res) {
    const dictValueMap = res

    let dictValueItemMap = {}
    for (var key in dictValueMap) {
      let dictValueItems = dictValueMap[key]

      dictValueItemMap[key] = {}

      for (var i = 0; i < dictValueItems.length; ++i) {
        let item = dictValueItems[i]
        dictValueItemMap[key][item.code] = item.name
      }
    }

    let data = {
      dictValueMap: dictValueMap,
      dictValueItemMap: dictValueItemMap
    }

    cb(data)
  })
}

module.exports = {
  request: request,
  uploadImage: uploadImage,
  login: login,
  loadDictValue: loadDictValue,
}
